# Standard PySceneDetect imports:
from scenedetect import VideoManager
from scenedetect import SceneManager

# For content-aware scene detection:
from scenedetect.detectors import ContentDetector

from moviepy.editor import VideoClip

from face_recognition import face_locations

import numpy as np


def find_scenes(video_path: str, threshold=30.0):
    # Create our video & scene managers, then add the detector.
    video_manager = VideoManager([video_path])
    scene_manager = SceneManager()
    scene_manager.add_detector(
        ContentDetector(threshold=threshold))

    # Improve processing speed by downscaling before processing.
    video_manager.set_downscale_factor()

    # Start the video manager and perform the scene detection.
    video_manager.start()
    scene_manager.detect_scenes(frame_source=video_manager)

    # Each returned scene is a tuple of the (start, end) timecode.
    return scene_manager.get_scene_list()


def subclip_by_scene(clip: VideoClip, scene):
    return clip.subclip(scene[0].get_timecode(), scene[1].get_timecode())


def sub_scene_clips(clip: VideoClip, scenes):
    return list(map(lambda scene: subclip_by_scene(clip, scene), scenes))

def has_face(image: np.ndarray,face_min_size=.01):
    faces = face_locations(image)
    if len(faces) != 1:
        return False
    return face_percentage(faces[0],image) >= face_min_size

def face_percentage(face_location,image: np.ndarray):
    h,w = image.shape[:2]
    t,r,b,l = face_location
    dw = r-l
    dh = b-t
    return dw*dh/w/h


def clip_fullface_detect(clip: VideoClip, samplings=3,face_min_size=.01):
    for t in np.linspace(.1, clip.duration-.1, samplings):
        frame = clip.get_frame(t)
        if not has_face(frame,face_min_size=face_min_size):
            return False
    return True
